package rm2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPDatagram 
{
	
	public static String messageSendAndReceive(String msg, int port, String address)	
	{
		int serverPort = port;
		String serverAddress = address;
		String reply_message = null;
		
		DatagramSocket aSocket = null;
		  try 
		  {
			  aSocket = new DatagramSocket();
			  byte [] m = msg.getBytes();
			  InetAddress aHost = InetAddress.getByName(serverAddress);			  
			  
			  // Send
			  DatagramPacket request = new DatagramPacket(m, msg.length(), aHost, serverPort);
			  aSocket.send(request);
			  
			  // Receive
			  byte[] buffer = new byte[1000];
			  DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
			  aSocket.receive(reply);
			  reply_message = new String(reply.getData()).trim();
			  System.out.println("datagram reply "+ reply_message);
			  
			  aSocket.close();
			}
		  catch(SocketException e)
		  {
			  System.out.println("Socket: " + e.getMessage());
		  }
		  catch (IOException e)
		  {
			  System.out.println("IO: " + e.getMessage());
		  }
		  finally 
		  {
			  if(aSocket != null) aSocket.close();
		  }
		  System.out.println("Reply: " + reply_message);
		  return reply_message;
	}

}
